const app = getApp()
let qCloud = require("../../index.js");

Page({
    /** 页面的初始数据 */
    data: {
        imgPath: qCloud.config.STATIC_IMAGE_PATH,
        queryMonth: null,
        staffId: null,
        wagesId: 0, // 工资ID
        wagesCode: "", // 工资编码
        wagesMonth: "", // 工资月份
        wagesTotal: 0, // 工资总额
        issuedWagesTotal: 0, // 已发工资总额
        unpaidWagesTotal: 0, // 未发工资总额
        pieceRate: 0, // 计件工资
        baseWages: null, // 底薪
        hourlyWage: null, // 计时工资
        commission: null, // 提成
        issuedWages: null, // 已发工资
        advanceWages: null, // 预支
        othersWagesTotal: 0, // 其他工资总额
        wagesOthersList: [], // 其他工资列表
        pieceRateTotal: 0, // 计件工资总额
        pieceRateList: [], // 计件工资列表
        showWagesModalStatus: false, // 工序模板对话框标记
        wagesTemplateList: [], // 工序模板列表-
        wagesTemplateName: "",
    },

    // 搜索
    bindQueryMonthChange(e) {
        let self = this;
        // 查询当月工资
        self.queryCurrentMonthWages(e.detail.value);
    },

    // 计算-工资总额
    countWagesTotal() {
        let self = this;

        // 其他工资总额 = 其他工资列表的工资总和
        let othersWagesTotal = 0;
        let wagesOthersList = self.data.wagesOthersList; // 其他工资列表
        for (let i = 0; i < wagesOthersList.length; i++) {
            let wagesOthers = wagesOthersList[i];
            if (wagesOthers.deletedMark) {
                continue;
            }
            if (wagesOthers.minus) {
                othersWagesTotal = self.formatValue(othersWagesTotal) - self.formatValue(wagesOthers.customWages);
            } else {
                othersWagesTotal = self.formatValue(othersWagesTotal) + self.formatValue(wagesOthers.customWages);
            }
        }

        // 工资总额 = 底薪 + 计时工资 + 提成 + 计件工资总额
        let wagesTotal = self.formatValue(self.data.baseWages) + self.formatValue(self.data.hourlyWage) + self.formatValue(self.data.commission) + self.formatValue(self.data.pieceRateTotal) + self.formatValue(othersWagesTotal);

        // 未发工资总额 = 工资总额 - 已发工资总额
        let unpaidWagesTotal = self.formatValue(wagesTotal) - self.formatValue(self.data.issuedWagesTotal);

        self.setData({
            wagesTotal: Number.parseFloat(wagesTotal.toFixed(2)),
            unpaidWagesTotal: Number.parseFloat(unpaidWagesTotal.toFixed(2)),
            othersWagesTotal: Number.parseFloat(othersWagesTotal.toFixed(2)),
        });
    },

    // 底薪
    baseWagesInput(e) {
        let self = this;
        let baseWages = e.detail.value

        self.setData({
            baseWages: baseWages
        });

        // 计算-工资总额
        self.countWagesTotal();
    },

    // 计时工资
    hourlyWageInput(e) {
        let self = this;
        let hourlyWage = e.detail.value

        self.setData({
            hourlyWage: hourlyWage
        });

        // 计算-工资总额
        self.countWagesTotal();
    },

    // 提成
    commissionInput(e) {
        let self = this;
        let commission = e.detail.value

        self.setData({
            commission: commission
        });

        // 计算-工资总额
        self.countWagesTotal();
    },

    // 计算-已发工资总额
    countIssuedWagesTotal() {
        let self = this;

        // 已发工资总额 = 已发工资 + 预支
        let issuedWagesTotal = self.formatValue(self.data.issuedWages) + self.formatValue(self.data.advanceWages);
        // 未发工资总额 = 工资总额 - 已发工资总额
        let unpaidWagesTotal = self.formatValue(self.data.wagesTotal) - self.formatValue(issuedWagesTotal);

        self.setData({
            issuedWagesTotal: Number.parseFloat(issuedWagesTotal.toFixed(2)),
            unpaidWagesTotal: Number.parseFloat(unpaidWagesTotal.toFixed(2)),
        });
    },

    // 发工资
    issuedWagesInput(e) {
        let self = this;
        let issuedWages = e.detail.value

        self.setData({
            issuedWages: issuedWages
        });

        // 计算-已发工资总额
        self.countIssuedWagesTotal();
    },

    // 预支
    advanceWagesInput(e) {
        let self = this;
        let advanceWages = e.detail.value

        self.setData({
            advanceWages: advanceWages
        });

        // 计算-已发工资总额
        self.countIssuedWagesTotal();
    },

    // 其他-工资项
    customNameInput(e) {
        let self = this;
        let value = e.detail.value;
        let index = e.currentTarget.dataset.index;
        self.data.wagesOthersList[index]["customName"] = value.trim();
        self.setData({
            wagesOthersList: self.data.wagesOthersList
        });
    },

    // 其他-工资
    customWagesInput(e) {
        let self = this;

        // let customWages = e.detail.value
        // if ("-" == customWages) {
        //     // 负号开头
        // } else {
        //     let reg = /^-?[0-9]+.?[0-9]*/;
        //     if (!reg.test(Number(customWages))) {
        //         self.setData({
        //             wagesOthersList: self.data.wagesOthersList
        //         });
        //         return;
        //     }
        // }

        let index = e.currentTarget.dataset.index;
        self.data.wagesOthersList[index]["customWages"] = e.detail.value;
        self.setData({
            wagesOthersList: self.data.wagesOthersList
        });

        // 计算-工资总额
        self.countWagesTotal();
    },

    // 其他-减
    customWagesMinus(e) {
        let self = this;
        let index = e.currentTarget.dataset.index;
        if (self.data.wagesOthersList[index]["minus"]) {
            self.data.wagesOthersList[index]["minus"] = false;
        } else {
            self.data.wagesOthersList[index]["minus"] = true;
        }
        self.setData({
            wagesOthersList: self.data.wagesOthersList
        });

        // 计算-工资总额
        self.countWagesTotal();
    },

    // 其他-新增
    addOthersWages(e) {
        let self = this;
        let wagesOthersList = self.data.wagesOthersList;
        let array = {
            customName: "",
            customWages: null,
            minus: false,
            deletedMark: false,
        };
        wagesOthersList.push(array);
        self.setData({
            wagesOthersList: wagesOthersList
        });

        // 计算-工资总额
        self.countWagesTotal();
    },

    // 其他-删除
    delOthersWages(e) {
        let self = this;
        let index = e.currentTarget.dataset.index;
        let wagesOthersList = self.data.wagesOthersList;

        if (wagesOthersList[index].wagesOthersId) {
            wagesOthersList[index].deletedMark = true;
        } else {
            wagesOthersList.splice(index, 1);
        }

        self.setData({
            wagesOthersList: wagesOthersList
        });

        // 计算-工资总额
        self.countWagesTotal();
    },

    // 显示对话框(工资模板)
    showWagesModal: function () {
        // 显示遮罩层
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        });
        this.animation = animation;
        animation.translateY(300).step();
        this.setData({
            animationData: animation.export(),
            showWagesModalStatus: true
        });
        setTimeout(function () {
            animation.translateY(0).step();
            this.setData({
                animationData: animation.export()
            });
        }.bind(this), 200);
    },

    // 隐藏对话框(工资模板)
    hideWagesModal: function () {
        // 隐藏遮罩层
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        });
        this.animation = animation;
        animation.translateY(300).step();
        this.setData({
            animationData: animation.export(),
        });
        setTimeout(function () {
            animation.translateY(0).step();
            this.setData({
                animationData: animation.export(),
                showWagesModalStatus: false
            });
        }.bind(this), 200);
    },

    // 导入工资模板
    importTemplate(e) {
        let self = this;
        let index = e.currentTarget.dataset.index;
        let wagesOthersList = []; // self.data.wagesOthersList;
        let subWagesTemplateInfoList = self.data.wagesTemplateList[index].subWagesTemplateInfoList;
        for (let i = 0; i < subWagesTemplateInfoList.length; i++) {
            let tmp = {
                customName: subWagesTemplateInfoList[i].templateName,
                customWages: subWagesTemplateInfoList[i].templateWages,
                minus: subWagesTemplateInfoList[i].minus,
                deletedMark: false,
            };
            wagesOthersList.push(tmp);
        }
        self.setData({
            wagesOthersList: wagesOthersList,
            showWagesModalStatus: false
        });

        // 计算-工资总额
        self.countWagesTotal();
    },

    // 工资模板名称
    wagesTemplateNameInput(e) {
        let self = this;
        self.setData({
            wagesTemplateName: e.detail.value.trim()
        });
    },

    // 提交工资模板
    saveTemplate(e) {
        let self = this;
        let wagesOthersList = self.data.wagesOthersList; // 其他工资列表

        let subWagesTemplateInfoList = [];
        for (let i = 0; i < wagesOthersList.length; i++) {
            let wagesOthers = wagesOthersList[i];
            if (wagesOthers.customName != "") {
                let subWagesTemplateInfo = {
                    templateName: wagesOthers.customName,
                    templateWages: wagesOthers.customWages,
                    minus: wagesOthers.minus,
                };
                subWagesTemplateInfoList.push(subWagesTemplateInfo);
            }
        }

        if (subWagesTemplateInfoList.length > 0) {
            let params = {
                wagesTemplateInfoList: [{
                    templateName: self.data.wagesTemplateName,
                    subWagesTemplateInfoList: subWagesTemplateInfoList,
                }]
            };
            app.fetchApis(self, qCloud.api.common_submitWagesTemplate, params, "POST", function (e) {
                let result = e.data;
                if (result.code == 200) {
                    wx.showToast({
                        title: "保存工资模板成功！",
                        icon: "success"
                    });
                    self.queryWagesTemplateList();
                }
            });
        } else {
            wx.showToast({
                title: "没有有效的工资项，无法保存为工资模板。",
                icon: "error"
            });
        }

        self.closePopupBox();
    },

    // 显示弹出框
    showPopupBox() {
        let self = this;
        self.setData({
            wagesTemplateName: "",
            popupBoxMark: true
        });
    },

    // 关闭弹出框
    closePopupBox() {
        let self = this;
        self.setData({
            wagesTemplateName: "",
            popupBoxMark: false
        });
    },

    /** 生命周期函数--监听页面加载 */
    onLoad: function (options) {
        let self = this;
        self.setData({
            queryMonth: options.queryMonth,
            staffId: options.staffId,
        });

        // 查询当月工资
        self.queryCurrentMonthWages(options.queryMonth);
        // 查询工资模板列表
        self.queryWagesTemplateList();
    },

    // 查询当月工资
    queryCurrentMonthWages(queryMonth) {
        let self = this;

        let params = {
            queryMonth: queryMonth,
            staffId: self.data.staffId,
        };

        app.fetchApis(self, qCloud.api.wages_queryCurrentMonthWages, params, "POST", function (e) {
            let result = e.data;

            if (result.code == 200) {
                let data = result.data;

                if (data.wagesId) {
                    // 未发工资总额 = 工资总额 - 已发工资总额
                    let unpaidWagesTotal = self.formatValue(data.wagesTotal) - self.formatValue(data.issuedWagesTotal);

                    self.setData({
                        wagesId: data.wagesId, // 工资ID
                        wagesCode: data.wagesCode, // 工资编码
                        wagesMonth: data.wagesMonth, // 工资月份
                        wagesTotal: data.wagesTotal, // 工资总额
                        issuedWagesTotal: data.issuedWagesTotal, // 已发工资总额
                        unpaidWagesTotal: Number.parseFloat(unpaidWagesTotal.toFixed(2)), // 未发工资总额
                        pieceRate: data.pieceRate, // 计件工资
                        baseWages: data.baseWages, // 底薪
                        hourlyWage: data.hourlyWage, // 计时工资
                        commission: data.commission, // 提成
                        issuedWages: data.issuedWages, // 已发工资
                        advanceWages: data.advanceWages, // 预支
                        othersWagesTotal: data.othersWagesTotal, // 其他工资总额
                        wagesOthersList: data.wagesOthersList, // 其他工资列表
                        pieceRateTotal: data.pieceRateTotal, // 计件工资总额
                        pieceRateList: data.pieceRateList, // 计件工资列表
                        queryMonth: queryMonth,
                    });
                } else {}
            }
        })
    },

    // 查询工资模板列表
    queryWagesTemplateList() {
        let self = this;

        let params = {};

        app.fetchApis(self, qCloud.api.common_queryWagesTemplateList, params, "POST", function (e) {
            let result = e.data;
            if (result.code == 200) {
                let data = result.data;

                self.setData({
                    wagesTemplateList: data.wagesTemplateInfoList,
                })
            }
        })
    },

    // 提交当月工资
    submitCurrentMonthWages() {
        let self = this;

        let title = self.checkParams();
        if (title != "") {
            wx.showToast({
                title: title,
                icon: "error"
            });
            return;
        }

        let params = {
            wagesId: self.data.wagesId, // 工资ID
            wagesCode: self.data.wagesId, // 工资编码
            wagesMonth: self.data.wagesMonth, // 工资月份
            wagesTotal: self.data.wagesTotal, // 工资总额
            issuedWagesTotal: self.data.issuedWagesTotal, // 已发工资总额
            baseWages: self.data.baseWages, // 底薪
            hourlyWage: self.data.hourlyWage, // 计时工资
            commission: self.data.commission, // 提成
            issuedWages: self.data.issuedWages, // 已发工资
            advanceWages: self.data.advanceWages, // 预支
            othersWagesTotal: self.data.othersWagesTotal, // 其他工资总额
            wagesOthersList: self.data.wagesOthersList, // 其他工资列表
        };

        app.fetchApis(self, qCloud.api.wages_submitCurrentMonthWages, params, "POST", function (e) {
            let result = e.data;

            if (result.code == 200) {
                wx.navigateBack({
                    delta: 1
                })
                // wx.navigateTo({
                //     url: "/pages/wages/index",
                // });
            }
        });
    },

    // 校验参数
    checkParams() {
        let self = this;
        if (Number(self.data.baseWages) < 0) {
            return "底薪不能小于0";
        }
        if (Number(self.data.hourlyWage) < 0) {
            return "计时工资不能小于0";
        }
        if (Number(self.data.commission) < 0) {
            return "提成不能小于0";
        }
        if (Number(self.data.issuedWages) < 0) {
            return "已发工资不能小于0";
        }
        if (Number(self.data.advanceWages) < 0) {
            return "预支不能小于0";
        }
        if (Number(self.data.issuedWagesTotal) < 0) {
            return "已发工资总额不能小于0";
        }
        return "";
    },

    // 格式值
    formatValue(value) {
        if (value) {
            return Number.parseFloat(value);
        }
        return 0;
    },
});
